<template>
  <div class="app-container">
    <el-card class="survey-stats">
      <div slot="header">
        <span>问卷统计分析</span>
        <el-button style="float: right; margin-left: 10px" type="primary" @click="goBack">返回</el-button>
        <el-button style="float: right" type="success" @click="exportData">导出数据</el-button>
      </div>
      
      <div class="stats-header">
        <h2 class="survey-title">{{ survey.title }} - 统计数据</h2>
        <div class="stats-info">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stats-card">
                <div class="stats-value">{{ survey.totalVisits }}</div>
                <div class="stats-label">访问人数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stats-card">
                <div class="stats-value">{{ survey.totalAnswers }}</div>
                <div class="stats-label">回收数量</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stats-card">
                <div class="stats-value">{{ survey.finishRate }}%</div>
                <div class="stats-label">完成率</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stats-card">
                <div class="stats-value">{{ survey.averageTime }}</div>
                <div class="stats-label">平均用时</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" style="margin-top: 20px;">
        <el-tab-pane label="数据概览" name="overview"></el-tab-pane>
        <el-tab-pane label="详细数据" name="details"></el-tab-pane>
        <el-tab-pane label="交叉分析" name="cross"></el-tab-pane>
      </el-tabs>
      
      <!-- 数据概览 -->
      <div v-if="activeTab === 'overview'" class="stats-overview">
        <div v-for="(question, index) in survey.questions" :key="index" class="question-stats">
          <div class="question-title">
            <span class="question-index">Q{{ index + 1 }}</span>
            <span class="question-text">{{ question.title }}</span>
            <span v-if="question.required" class="question-required">*</span>
          </div>
          
          <!-- 单选题或多选题统计 -->
          <div v-if="question.type === 'radio' || question.type === 'checkbox'" class="chart-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="chartContainer" class="chart" :id="'chart-' + index"></div>
              </el-col>
              <el-col :span="12">
                <div class="options-stats">
                  <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                    <div class="option-label">{{ option.label }}</div>
                    <div class="option-bar">
                      <div class="progress-bar" :style="{width: option.percentage + '%', backgroundColor: getChartColor(optIndex)}"></div>
                    </div>
                    <div class="option-value">{{ option.count }} ({{ option.percentage }}%)</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <!-- 评分题统计 -->
          <div v-else-if="question.type === 'rate'" class="rating-stats">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="rating-summary">
                  <div class="average-score">{{ questionData[index].averageScore }}</div>
                  <div class="total-participants">共{{ questionData[index].totalParticipants }}人参与</div>
                  <el-rate 
                    v-model="questionData[index].averageScore" 
                    disabled
                    :max="question.max || 5"
                    :texts="question.texts || ['很差', '较差', '一般', '较好', '很好']"
                    show-text>
                  </el-rate>
                </div>
              </el-col>
              <el-col :span="16">
                <div class="rating-distribution">
                  <div v-for="i in (question.max || 5)" :key="i" class="rating-item">
                    <div class="rating-label">{{ i }} 分</div>
                    <div class="rating-bar">
                      <div class="progress-bar" :style="{width: questionData[index].distribution[i-1].percentage + '%', backgroundColor: getChartColor(i-1)}"></div>
                    </div>
                    <div class="rating-value">{{ questionData[index].distribution[i-1].count }} ({{ questionData[index].distribution[i-1].percentage }}%)</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <!-- 文本题统计 -->
          <div v-else-if="question.type === 'text'" class="text-stats">
            <div class="text-summary">
              <div class="text-count">共收到 {{ questionData[index].answerCount }} 条回答</div>
              <div class="text-word-cloud" :id="'wordcloud-' + index"></div>
              <el-button size="small" type="primary" @click="viewTextAnswers(index)">查看所有回答</el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 详细数据 -->
      <div v-else-if="activeTab === 'details'" class="stats-details">
        <div class="table-tools">
          <el-button type="primary" size="small" icon="el-icon-download" @click="exportData">导出数据</el-button>
          <el-button type="info" size="small" icon="el-icon-refresh" @click="refreshData">刷新</el-button>
        </div>
        
        <el-table
          v-loading="loading"
          :data="answersList"
          border
          style="width: 100%"
          max-height="600">
          <el-table-column type="index" width="50" align="center" label="#"></el-table-column>
          <el-table-column prop="submitTime" label="提交时间" width="180" sortable></el-table-column>
          <el-table-column prop="ipAddress" label="IP地址" width="140"></el-table-column>
          <el-table-column prop="device" label="设备类型" width="100"></el-table-column>
          <el-table-column prop="timeSpent" label="用时" width="100" sortable></el-table-column>
          <el-table-column v-for="(question, index) in survey.questions" :key="index" :label="'Q' + (index + 1)" :min-width="120">
            <template slot-scope="scope">
              <span v-if="question.type === 'text'">
                <el-tooltip :content="scope.row.answers[index]" placement="top" :disabled="!scope.row.answers[index]">
                  <span>{{ scope.row.answers[index] ? (scope.row.answers[index].length > 20 ? scope.row.answers[index].substring(0, 20) + '...' : scope.row.answers[index]) : '-' }}</span>
                </el-tooltip>
              </span>
              <span v-else-if="question.type === 'checkbox'">
                {{ scope.row.answers[index] ? scope.row.answers[index].join(', ') : '-' }}
              </span>
              <span v-else>
                {{ scope.row.answers[index] || '-' }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getAnswersList"
        />
      </div>
      
      <!-- 交叉分析 -->
      <div v-else-if="activeTab === 'cross'" class="stats-cross">
        <div class="cross-config">
          <el-form :model="crossAnalysis" label-width="120px">
            <el-form-item label="维度一">
              <el-select v-model="crossAnalysis.dimension1" placeholder="请选择维度一" style="width: 100%;">
                <el-option
                  v-for="(question, index) in selectableQuestions"
                  :key="index"
                  :label="'Q' + (question.index + 1) + ': ' + question.title"
                  :value="question.index">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="维度二">
              <el-select v-model="crossAnalysis.dimension2" placeholder="请选择维度二" style="width: 100%;">
                <el-option
                  v-for="(question, index) in selectableQuestions"
                  :key="index"
                  :label="'Q' + (question.index + 1) + ': ' + question.title"
                  :value="question.index"
                  :disabled="question.index === crossAnalysis.dimension1">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="generateCrossAnalysis">生成分析</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <div v-if="hasCrossData" class="cross-result">
          <div class="cross-chart" id="cross-chart"></div>
        </div>
      </div>
    </el-card>
    
    <!-- 文本回答弹窗 -->
    <el-dialog title="文本回答列表" :visible.sync="textAnswersVisible" width="650px">
      <div class="text-answers-list">
        <div v-for="(answer, index) in textAnswers" :key="index" class="text-answer-item">
          <div class="answer-info">
            <span class="answer-index">#{{ index + 1 }}</span>
            <span class="answer-time">{{ answer.submitTime }}</span>
          </div>
          <div class="answer-content">{{ answer.content }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "SurveyStats",
  data() {
    return {
      surveyId: null,
      survey: {
        title: "员工满意度调查问卷",
        totalVisits: 45,
        totalAnswers: 32,
        finishRate: 71,
        averageTime: "3分42秒",
        questions: [
          {
            title: "您对公司工作环境的满意度是？",
            type: "radio",
            required: true,
            options: [
              { label: "非常满意", value: "5", count: 15, percentage: 47 },
              { label: "比较满意", value: "4", count: 10, percentage: 31 },
              { label: "一般", value: "3", count: 5, percentage: 16 },
              { label: "不太满意", value: "2", count: 2, percentage: 6 },
              { label: "非常不满意", value: "1", count: 0, percentage: 0 }
            ]
          },
          {
            title: "您认为公司需要改善的方面有哪些？（多选）",
            type: "checkbox",
            required: true,
            options: [
              { label: "工作环境", value: "environment", count: 8, percentage: 25 },
              { label: "薪资福利", value: "salary", count: 20, percentage: 63 },
              { label: "培训发展", value: "training", count: 15, percentage: 47 },
              { label: "团队氛围", value: "team", count: 5, percentage: 16 },
              { label: "管理制度", value: "management", count: 12, percentage: 38 },
              { label: "其他", value: "other", count: 3, percentage: 9 }
            ]
          },
          {
            title: "请对公司的管理制度进行评分",
            type: "rate",
            required: true,
            max: 5
          },
          {
            title: "请描述您对公司未来发展的建议",
            type: "text",
            required: false
          }
        ]
      },
      // 问题数据
      questionData: [
        {},
        {},
        {
          averageScore: 3.7,
          totalParticipants: 32,
          distribution: [
            { score: 1, count: 2, percentage: 6 },
            { score: 2, count: 3, percentage: 9 },
            { score: 3, count: 7, percentage: 22 },
            { score: 4, count: 12, percentage: 38 },
            { score: 5, count: 8, percentage: 25 }
          ]
        },
        {
          answerCount: 25,
          wordCloud: ["培训", "福利", "发展", "环境", "晋升", "沟通", "透明", "绩效"]
        }
      ],
      // 当前标签页
      activeTab: "overview",
      // 是否加载中
      loading: false,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 答卷列表
      answersList: [],
      // 交叉分析参数
      crossAnalysis: {
        dimension1: null,
        dimension2: null
      },
      // 是否有交叉分析数据
      hasCrossData: false,
      // 文本回答弹窗
      textAnswersVisible: false,
      // 文本回答列表
      textAnswers: []
    };
  },
  computed: {
    // 可选择的问题（单选题和多选题）
    selectableQuestions() {
      return this.survey.questions
        .map((question, index) => ({ 
          index,
          title: question.title, 
          type: question.type
        }))
        .filter(question => question.type === 'radio' || question.type === 'checkbox');
    }
  },
  created() {
    this.surveyId = this.$route.params.id;
    // 这里应该调用后端接口获取问卷数据和统计数据，暂时使用模拟数据
    this.getAnswersList();
  },
  mounted() {
    // 模拟图表渲染
    this.$message.info("数据加载中，图表渲染需要引入图表库");
  },
  methods: {
    goBack() {
      this.$router.push("/system/survey");
    },
    exportData() {
      this.$message.success("数据导出成功");
    },
    handleTabClick() {
      if (this.activeTab === 'details') {
        this.getAnswersList();
      }
    },
    // 获取图表颜色
    getChartColor(index) {
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#B983FF'];
      return colors[index % colors.length];
    },
    // 查询答卷列表
    getAnswersList() {
      this.loading = true;
      // 这里应该调用后端接口，暂时使用模拟数据
      setTimeout(() => {
        // 生成模拟数据
        this.answersList = [];
        for (let i = 1; i <= 32; i++) {
          const item = {
            id: i,
            submitTime: this.randomDate(new Date(2023, 2, 1), new Date(2023, 2, 15)),
            ipAddress: `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`,
            device: Math.random() > 0.7 ? 'Mobile' : 'Desktop',
            timeSpent: `${Math.floor(Math.random() * 10) + 1}分${Math.floor(Math.random() * 60)}秒`,
            answers: [
              Math.floor(Math.random() * 5) + 1, // 单选题
              this.randomCheckboxAnswers(['environment', 'salary', 'training', 'team', 'management', 'other']), // 多选题
              Math.floor(Math.random() * 5) + 1, // 评分题
              this.randomTextAnswer() // 文本题
            ]
          };
          this.answersList.push(item);
        }
        this.total = this.answersList.length;
        this.loading = false;
      }, 500);
    },
    // 生成随机日期
    randomDate(start, end) {
      const date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
      return date.toLocaleString();
    },
    // 生成随机多选答案
    randomCheckboxAnswers(options) {
      const count = Math.floor(Math.random() * 3) + 1; // 1到3个选项
      const shuffled = [...options].sort(() => 0.5 - Math.random());
      return shuffled.slice(0, count);
    },
    // 生成随机文本答案
    randomTextAnswer() {
      const texts = [
        "希望公司能够提供更多的培训机会",
        "建议改善办公环境，提高工作效率",
        "期待更加透明的晋升机制",
        "福利待遇可以再提高一些",
        "加强团队建设，增强凝聚力",
        "希望有更多跨部门交流的机会",
        "工作压力较大，希望能够适当调整",
        "",
        "提高绩效评估的公平性",
        "增加员工关怀活动"
      ];
      return texts[Math.floor(Math.random() * texts.length)];
    },
    // 刷新数据
    refreshData() {
      this.getAnswersList();
    },
    // 生成交叉分析
    generateCrossAnalysis() {
      if (this.crossAnalysis.dimension1 === null || this.crossAnalysis.dimension2 === null) {
        this.$message.warning("请选择两个维度进行交叉分析");
        return;
      }
      
      this.loading = true;
      // 这里应该调用后端接口，暂时设置标志位
      setTimeout(() => {
        this.hasCrossData = true;
        this.loading = false;
        this.$message.success("交叉分析数据生成成功");
      }, 800);
    },
    // 查看文本回答
    viewTextAnswers(questionIndex) {
      // 从答卷列表中提取文本回答
      this.textAnswers = this.answersList
        .filter(item => item.answers[questionIndex])
        .map(item => ({
          submitTime: item.submitTime,
          content: item.answers[questionIndex]
        }));
      this.textAnswersVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.survey-stats {
  .stats-header {
    margin-bottom: 30px;
    
    .survey-title {
      text-align: center;
      margin-bottom: 20px;
    }
    
    .stats-info {
      margin-top: 20px;
      
      .stats-card {
        background-color: #f8f9fa;
        border-radius: 6px;
        padding: 15px;
        text-align: center;
        
        .stats-value {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
          margin-bottom: 5px;
        }
        
        .stats-label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  .question-stats {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px dashed #EBEEF5;
    
    .question-title {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: bold;
      
      .question-index {
        color: #409EFF;
        margin-right: 8px;
      }
      
      .question-required {
        color: #F56C6C;
        margin-left: 4px;
      }
    }
    
    .chart-container {
      .chart {
        height: 300px;
      }
      
      .options-stats {
        .option-item {
          display: flex;
          align-items: center;
          margin-bottom: 15px;
          
          .option-label {
            width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .option-bar {
            flex: 1;
            height: 16px;
            background-color: #EBEEF5;
            border-radius: 8px;
            overflow: hidden;
            margin: 0 10px;
            
            .progress-bar {
              height: 100%;
              border-radius: 8px;
            }
          }
          
          .option-value {
            width: 80px;
            text-align: right;
          }
        }
      }
    }
    
    .rating-stats {
      .rating-summary {
        text-align: center;
        padding: 20px;
        
        .average-score {
          font-size: 48px;
          font-weight: bold;
          color: #F7BA2A;
          line-height: 1;
        }
        
        .total-participants {
          margin: 10px 0 15px;
          color: #909399;
        }
      }
      
      .rating-distribution {
        .rating-item {
          display: flex;
          align-items: center;
          margin-bottom: 15px;
          
          .rating-label {
            width: 50px;
          }
          
          .rating-bar {
            flex: 1;
            height: 16px;
            background-color: #EBEEF5;
            border-radius: 8px;
            overflow: hidden;
            margin: 0 10px;
            
            .progress-bar {
              height: 100%;
              border-radius: 8px;
            }
          }
          
          .rating-value {
            width: 80px;
            text-align: right;
          }
        }
      }
    }
    
    .text-stats {
      .text-summary {
        text-align: center;
        
        .text-count {
          margin-bottom: 15px;
          color: #606266;
        }
        
        .text-word-cloud {
          height: 200px;
          margin-bottom: 15px;
          background-color: #f8f9fa;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:before {
            content: "词云图(需集成词云库)";
            color: #909399;
          }
        }
      }
    }
  }
  
  .stats-details {
    .table-tools {
      margin-bottom: 15px;
    }
  }
  
  .stats-cross {
    .cross-config {
      max-width: 600px;
      margin: 0 auto 30px;
    }
    
    .cross-result {
      .cross-chart {
        height: 400px;
        background-color: #f8f9fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:before {
          content: "交叉分析图表(需集成图表库)";
          color: #909399;
        }
      }
    }
  }
}

.text-answers-list {
  max-height: 400px;
  overflow-y: auto;
  
  .text-answer-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #EBEEF5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .answer-info {
      margin-bottom: 5px;
      
      .answer-index {
        font-weight: bold;
        margin-right: 10px;
      }
      
      .answer-time {
        color: #909399;
        font-size: 12px;
      }
    }
    
    .answer-content {
      color: #606266;
      line-height: 1.5;
    }
  }
}
</style> 